package javango.db;


import org.apache.commons.logging.LogFactory;

/**
 * Provides a framework for paginating a list of objects in a few lines of code.
 * 
 * @author johns
 *
 */
public class QuerySetPaginator<T> extends AbstractPaginator<T> implements Paginator<T> {

	QuerySet<T> qs;
	public QuerySetPaginator(QuerySet<T> qs, int perPage) {
		super(perPage);
		this.qs = qs.clone();		
	}

	/* (non-Javadoc)
	 * @see javango.db.Paginator#getPage(int)
	 */
	public QuerySetPage<T> getPage(int number) {
		try {
			number = this.validateNumber(number);
			int bottom = (number - 1) * this.perPage;
			int top = bottom + this.perPage;
			if (top + this.getOrphans() >= this.getCount()) {
				top = this.getCount();
			}
			return new QuerySetPage<T>(this.qs.limit(bottom,top), number, this);
		} catch (ManagerException e) {
			LogFactory.getLog(QuerySetPaginator.class).error(e,e);
			return null;
		}
	}
	
	/* (non-Javadoc)
	 * @see javango.db.Paginator#getCount()
	 */
	public int getCount() {
		try {
			return new Long(qs.count()).intValue();
		} catch (ManagerException e) {
			LogFactory.getLog(QuerySetPaginator.class).error(e,e);
		}
		return 0;
	}
}
